﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualBasic.FileIO;

namespace SSISFromCode.Helpers
{

    internal class FlatFileColumnReader
    {

        internal List<string> Columns( IFlatFileColumnOptions columnOptions )
        {
            var tfp = new TextFieldParser( columnOptions.Path )
            {
                TextFieldType = (FieldType)columnOptions.ColumnFieldType,
                FieldWidths = columnOptions.ColumnWidths == null ? null : columnOptions.ColumnWidths.ToArray()
            };
            tfp.Delimiters = new string[] { columnOptions.Delimiter };
            return Columns( tfp, columnOptions );
        }

        private List<string> Columns( TextFieldParser tfp, IFlatFileColumnOptions columnOptions )
        {
            var result = tfp.ReadFields().ToList();
            if ( columnOptions.ColumnNamesInFirstRow )
            {
                result.ForEach( c => c = c.TrimEnd() );
            }
            else
            {
                /// If column options didn't specify a header row, then our result should contain the proper field count, 
                /// but the names will just be the values of the first data row.  That's not what we want.
                for ( int i = 0; i < result.Count; i++ )
                {
                    result[i] = "Column" + Convert.ToString( i + 1 );  // Make names 1 based
                }
            }
            return result;
        }

    }

}
